using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Terra.Core.Common.ErrorCodes.Models;

namespace Terra.Core.Common.ErrorCodes.Providers;

/// <summary>
/// 默认错误码提供者实现
/// </summary>
public class DefaultErrorCodeProvider : IErrorCodeProvider
{
    private readonly ConcurrentDictionary<string, ErrorCodeInfo> _errorCodes;

    public DefaultErrorCodeProvider()
    {
        _errorCodes = new ConcurrentDictionary<string, ErrorCodeInfo>();
    }

    /// <inheritdoc />
    public ErrorCodeInfo GetErrorInfo(string code)
    {
        if (!_errorCodes.TryGetValue(code, out var errorInfo))
        {
            throw new KeyNotFoundException($"错误码 {code} 未注册");
        }

        return errorInfo;
    }

    /// <inheritdoc />
    public void RegisterErrorCode(string code, ErrorCodeInfo info)
    {
        if (string.IsNullOrWhiteSpace(code))
        {
            throw new ArgumentException("错误码不能为空", nameof(code));
        }

        if (info == null)
        {
            throw new ArgumentNullException(nameof(info));
        }

        if (string.IsNullOrWhiteSpace(info.Message))
        {
            throw new ArgumentException("错误消息不能为空", nameof(info));
        }

        if (!_errorCodes.TryAdd(code, info))
        {
            throw new InvalidOperationException($"错误码 {code} 已存在");
        }
    }

    /// <inheritdoc />
    public bool Exists(string code)
    {
        return _errorCodes.ContainsKey(code);
    }

    /// <inheritdoc />
    public IReadOnlyDictionary<string, ErrorCodeInfo> GetAllErrorCodes()
    {
        return _errorCodes;
    }
}